<?php
    include_once 'database.php';
    include_once 'session_start.php';
    if($_GET["change"]=="pass"){
        $query="SELECT Password FROM users WHERE UserId=".$_GET["id"];
        $g_pass=$db -> query($query);
        $pass= $g_pass -> fetch_assoc();
        if($_POST["old_pass"]==$pass["Password"]){
            if($_POST["new_pass"]==$_POST["cf_pass"]){
                $query = "UPDATE users SET Password=? WHERE UserId=".$_GET["id"];
                $stmt=$db->prepare($query);
                $stmt->bind_param('s',$_POST["new_pass"]);
                $stmt->execute();
                $_SESSION["H7_Library_Message"]="Det lykkedes at ændre dit password";
                header('Location:user.php?id='.$_GET["id"].'&pass=change');
                die;   
            }else{
                $_SESSION["H7_Library_Message"]="Det nye password matchede ikke bekræftelsen";
                header('Location:user.php?id='.$_GET["id"].'&pass=change');
                die;                
            }
        }else{
            $_SESSION["H7_Library_Message"]="Nuværende og indskrevne password matchede ikke";
            header('Location:user.php?id='.$_GET["id"].'&pass=change');
            die;
        }
    }else{
        $f_name = $_POST["F_Name"];
        $l_name = $_POST["L_Name"];
        $email = $_POST["E-mail"];
        $country = $_POST["Country"];
        $address = $_POST["Address"];
        $postcode = $_POST["Postal_Code"];
        
        $error = false;
        foreach ($_POST as $k => $v) {
            $_SESSION["Update_User"][$k]=$v;
            if(empty($v)){
                $error = true;
            }    
        }
        if($error==true){
            $_SESSION["H7_Library_Message"]="Alle felter skal være udfyldt";
            header('Location:user.php?id='.$_GET["id"]);
           die;           
        }
        $exp = explode('.', $email);
        $ext = end($exp);    
        $at = explode('@', $email);
        $domain = end($at);
        $dot = explode('.', $domain);        
        if(strlen($ext)>4||strpos($email,'@')==false || count($at)>2 || count($dot)>2){
            $_SESSION["H7_Library_Message"]="Den givne email var ikke valid";
            header('Location:user.php?id='.$_GET["id"]);
            die;    
        }
        $query= "UPDATE users SET FirstName=?, LastName=?, Email=?, Address=?, Country=?, PostalCode=? WHERE UserId=".$_GET["id"];
        $stmt = $db->prepare($query);
        $stmt -> bind_param('ssssss',$f_name,$l_name,$email,$address,$country,$postcode);
        $stmt -> execute();
        
        unset($_SESSION["Update_User"]);
        $_SESSION["H7_Library_Message"]="Det lykkedes at opdatere dine kontakt oplysninger";
        header('Location:user.php?id='.$_GET["id"]);
    }
?>